using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using RayDen.Library.Components.Surface;
using RayDen.Library.Components.SystemComponents;
using RayDen.Library.Data;
using RayDen.Library.Entity.Frames;
using RayDen.Library.Entity.Scene;

namespace RayDen.RayEngine.Scene
{
    public partial class FrameMaterialBuilder
    {
        private FrameMaterialInfo[] items;
        private SurfaceMaterial[] surfMats;
        private static Dictionary<string, Func<MaterialInfo, SurfaceMaterial>> overrides;


        static FrameMaterialBuilder()
        {
            InitOverrides();
        }

        public FrameMaterialBuilder(FrameMaterialInfo[] items)
        {
            this.items = items;
            surfMats = this.items.Select(SurfaceMaterials.CreateFrameMaterial).ToArray();
            //ApplyMaterialOverrides(surfMats, overrides);
        }

        public IEnumerable<MaterialInfo> GetMaterialInfos()
        {
            return surfMats.Select(surfMat => surfMat.First.MaterialData);
        }

        public SurfaceMaterial[] Materials
        {
            get { return this.surfMats; }
        }

        public static void ApplyMaterialOverrides(SurfaceMaterial[] surfMats)
        {
            ApplyMaterialOverrides(surfMats, overrides);
        }


        public static void ApplyMaterialOverrides(SurfaceMaterial[] surfMats, RayEngineScene scene)
        {
            ApplyMaterialOverrides(surfMats, overrides);
            OverrideTextures(scene.OptTextures, scene.texturesMap);
        }



        public static void ApplyMaterialOverrides(SurfaceMaterial[] surfMats, Dictionary<string, Func<MaterialInfo, SurfaceMaterial>> overrideFuncs)
        {

            for (int index = 0; index < surfMats.Length; index++)
            {
                if (surfMats[index] == null)
                    continue;
                if (overrideFuncs.ContainsKey(surfMats[index].Name))
                {
                    var newMat = overrideFuncs[surfMats[index].Name](surfMats[index].First.MaterialData);
                    if (newMat != null)
                    {
                        Tracer.TraceLine(string.Format("$!$ Material override-{2} - {0} to {1}", surfMats[index].First.GetType().Name, newMat.First.GetType().Name, surfMats[index].Name));
                        surfMats[index] = newMat;
                    }
                }
            }

        }

        internal void CreateRayEngineMaterials(RayEngineScene rayEngineScene)
        {
            throw new NotImplementedException();
        }
    }
}